package jvmtest.RemoteExeDemo;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Tom
 * @Date: 2022/02/08/11:30
 * @Description:
 */

import java.lang.reflect.Method;

/**
 *@ClassName JavaclassExecuter
 *@Description
 *@Author 王琛
 *@Date 2022/2/8 11:30
 @Version 1.0
 */
public class JavaclassExecuter {
 /**
  * 执行外部传过来的代表一个Java类的byte数组
  * 将输入类的byte数组中代表java.lang.System的CONSTANT_Utf8_info常量修改为劫持后的HackSystem类
  * 执行方法为该类的static main(String[] args)方法，输出结果为该类向System.out/err输出的信息
  * @param classByte 代表一个Java类的Byte数组
  * @return 执行结果
  * */
    public static String execute(byte[] classByte){
        HackSystem.clearBuffer();
        ClassModifier cm = new ClassModifier(classByte);
        byte[] modiBytes = cm.modifyUTF8Constants("java/lang/System", "org/fenixsoft/classloading/execute/");
        HotSwapClassLoader loader = new HotSwapClassLoader();
        Class clazz = loader.loadByte(modiBytes);
        try {
            Method method = clazz.getMethod("main",new Class[] {
              String[].class
            });
        } catch (Throwable e) {
            e.printStackTrace(HackSystem.out);
        }
        return HackSystem.getBufferString();
    }
}
